package com.tianma315.web.wx.controller;

import com.alibaba.fastjson.JSONObject;

import com.tianma315.core.common.service.ConfigService;
import com.tianma315.core.tymenu.domain.TyMenuDataDO;
import com.tianma315.core.tymenu.service.TyMenuDataService;
import com.tianma315.core.tymenu.service.TyMenuService;
import com.tianma315.core.wx.domain.WxUserInfoDO;
import com.tianma315.core.wx.service.WxUserInfoService;
import com.tianma315.web.common.base.BaseController;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.*;

import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping("/wx")
public class WechatController extends BaseController {

    @Autowired
    private ConfigService configService;

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WxUserInfoService wxUserInfoService;

    @Autowired
    private TyMenuDataService tyMenuDataService;

    @Autowired
    private TyMenuService tyMenuService;

    @GetMapping("/authorize/{number}")
    public String authorize(@PathVariable("number") String number) {
//        if(StringUtils.isBlank(userId)){
//            return "error/403";
//        }
        String url = configService.getValuByKey("redirect_url");
        log.info("=============================微信授权回调地址: " + url);
        String state = "";
//        if(StringUtils.isNotBlank(templateUrl)){
//            state = userId + "," + templateUrl;
//        }else{
//            state = userId;
//        }
        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, number);
        return "redirect:" + redirectUrl;
    }

    @GetMapping("/userInfo")
    public ModelAndView userInfo(@RequestParam("code") String code,
                                 @RequestParam("state") String state,
                                 HttpSession session) throws Exception {
        log.info("============================code: " + code);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        WxMpUser wxMpUser = new WxMpUser();
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            log.info("wxMpOAuth2AccessToken = " + wxMpOAuth2AccessToken);
        } catch (WxErrorException e) {
            log.error("【微信网页授权】{}", e);
            throw new Exception("微信页面授权失败!");
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        if (StringUtils.isBlank(openId)) {
            log.error("【微信网页授权】返回的openId为null");
            throw new Exception("微信页面授权失败!");
        }
        WxUserInfoDO wxUserInfoDO = wxUserInfoService.getWxUserInfoByOpenId(openId);
        log.info("从数据查出的用户信息:" + wxUserInfoDO);
        String[] split = state.split(",");
        String number = split[0];
        log.info("number:"+number);
//        session.setAttribute("userId", Long.parseLong(split[0]));
        if (wxUserInfoDO == null) {
            log.info("从数据查出的用户信息为null");
            WxUserInfoDO wxUser = new WxUserInfoDO();
            wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
            log.info("wxMpUser " + wxMpUser);
            wxUser.setOpenId(openId);
            wxUser.setNickname(wxMpUser.getNickname());
            wxUser.setSex(wxMpUser.getSex());
            wxUser.setProvince(wxMpUser.getProvince());
            wxUser.setCity(wxMpUser.getCity());
            wxUser.setCountry(wxMpUser.getCountry());
            wxUser.setHeadimgurl(wxMpUser.getHeadImgUrl());
            wxUser.setCreatedDate(new Date());
            wxUser.setLastUpdateDate(new Date());
            wxUserInfoService.insert(wxUser);
            log.info("微信获取用户信息:wxUserInfoDO " + wxUser);
            log.info("根据requrst获取ip 得到地址 :wxUserInfoDO " + wxUserInfoDO);

        } else {
            wxUserInfoDO.setLastUpdateDate(new Date());
            wxUserInfoService.updateById(wxUserInfoDO);
        }
        session.setAttribute("openId", openId);
        log.info("==================================userInf中 openid = " + openId);

        JSONObject result = wxUserInfoService.getData(number,openId);
        ModelAndView modelAndView = new ModelAndView("wx/result");
        modelAndView.addObject("result",result);
        return modelAndView;
//        return number;
    }


    @GetMapping("/getData")
    public ResponseEntity<JSONObject> getData(@RequestParam("code") String code) throws Exception {
        JSONObject result = wxUserInfoService.getData(code,"ss");
        return ResponseEntity.ok(result);
//        return number;
    }

    @GetMapping("/getInfoData")
    public ModelAndView getInfoData(@RequestParam("code") String code) throws Exception {
        JSONObject result = wxUserInfoService.getData(code,"ss");
        ModelAndView modelAndView = new ModelAndView("wx/result");
        modelAndView.addObject("result",result);
        return modelAndView;
//        return number;
    }

    @GetMapping("/getTyMenuDataById/{menuDataId}")
    String getTyMenuDataById(@PathVariable("menuDataId") Integer menuDataId,Model model){
        TyMenuDataDO tyMenuData = tyMenuDataService.selectById(menuDataId);
        String[] imgList = tyMenuData.getDataValue().split(",");
        model.addAttribute("tyMenuData", tyMenuData);
        model.addAttribute("imgList",imgList);
        return "wx/trace-report-img";
    }

    @GetMapping("/checkCode")
    @ResponseBody
    JSONObject checkCode(@RequestParam("code") String code, Model model){
        JSONObject result = wxUserInfoService.checkCode(code);
        return result;
    }

}
